package com.usian.controller;

import com.usian.CartFeign;
import com.usian.CookieUtils;
import com.usian.JsonUtils;
import com.usian.Result;
import com.usian.feign.ItemFeign;
import com.usian.pojo.TbItem;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@RequestMapping("frontend/cart")
@RestController
public class CartController {

    @Autowired
    private ItemFeign itemFeign;

    @Autowired
    private CartFeign cartFeign;

    @Value("${CART_COOKIE_KEY}")
    private String CART_COOKIE_KEY;

    @Value("${CART_COOKIE_EXPIRE}")
    private long CART_COOKIE_EXPIRE;


    /**
     * 添加购物车
     *
     * @param userId
     * @param itemId
     * @param num
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/addItem")
    public Result addItem( Long itemId,String userId,@RequestParam(defaultValue = "1") Integer num,
                          HttpServletRequest request, HttpServletResponse response){
//        0：判断用户是否登录
        if (StringUtils.isBlank(userId)){
//            未登录
//        1：查询购物车map<itemId,tbitem>
            Map<String, TbItem> itemMap = this.getCartFromCookie(request);
//        2：购物车添加  有  改  num  数量   没有  map  put
            this.addItemToCart(itemMap,itemId,num);
//        3：map购物车  添加到cookie
            this.addClientCookie(request,response,itemMap);
            return Result.ok();
        }else {
//            已登录
//            1:查询购物车
            Map<String, TbItem> carts = this.getCartFromRedis(userId);
//            2:添加购物车
            this.addItemToCart(carts,itemId,num);
//            3：map购物车  添加到redis
            boolean result = this.addClientRedis(carts, userId);
            if (result) {
                return Result.ok();
            }
        }

        return Result.error("添加购物车失败");
    }

    /**
     * 查看购物车
     *
     * @param userId
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/showCart")
    public Result showCart(String userId ,HttpServletRequest request,HttpServletResponse response){
//        判断用户是否登录
        ArrayList<TbItem> tbItems = new ArrayList<>();
        if (StringUtils.isBlank(userId)) {
//            用户未登录
            Map<String, TbItem> cookie = this.getCartFromCookie(request);
            Set<String> keySet = cookie.keySet();
            for (String key : keySet) {
                tbItems.add(cookie.get(key));
            }
            return Result.ok(tbItems);
        }else {
//            用户已登录
            Map<String, TbItem> redisMap = this.getCartFromRedis(userId);
            Set<String> keySet = redisMap.keySet();
            for (String key : keySet) {
                tbItems.add(redisMap.get(key));
            }
            if (tbItems.size()>0){
                return Result.ok(tbItems);
            }
        }
        return Result.error("查询失败");
    }

    @RequestMapping("/updateItemNum")
    public Result updateItemNum(String userId,Long itemId,
                                Integer num,HttpServletRequest request,
                                HttpServletResponse response){
        if (StringUtils.isBlank(userId)){
//            未登录
//            获取cookie购物车的信息
            Map<String, TbItem> tbItemMap = this.getCartFromCookie(request);
//            进行信息修改
            TbItem tbItem = tbItemMap.get(itemId.toString());
            tbItem.setNum(num);
            tbItemMap.put(itemId.toString(), tbItem);
//            将修改后的信息写入cookie
            addClientCookie(request,response, tbItemMap);
            return Result.ok();
        }else {
//            已登录
            //            获取redis购物车的信息
            Map<String, TbItem> tbItemMap = this.getCartFromRedis(userId);
//            进行信息修改
            TbItem tbItem = tbItemMap.get(itemId.toString());
            tbItem.setNum(num);
            tbItemMap.put(itemId.toString(), tbItem);
//            将修改后的信息写入redis
            this.addClientRedis(tbItemMap,userId);
            if (tbItem!=null) {
                return Result.ok();
            }
        }
        return Result.error("修改失败");
    }

    /**
     * 删除购物车
     *
     * @param userId
     * @param itemId
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("deleteItemFromCart")
    public Result deleteItemFromCart(String userId,Long itemId,HttpServletRequest request,HttpServletResponse response){
        if (StringUtils.isBlank(userId)){
//            未登录
            Map<String, TbItem> cookie = getCartFromCookie(request);
            cookie.remove(itemId.toString());
            addClientCookie(request,response,cookie);
            return Result.ok("删除成功");
        }else {
//            已登录
            Map<String, TbItem> redisMap = getCartFromRedis(userId);
            redisMap.remove(itemId.toString());
            addClientRedis(redisMap,userId);
            if (redisMap.size()>0){
                return Result.ok("删除成功");
            }
        }
        return Result.error("删除失败");
    }

    /**
     * 查询cookie中的购物车信息
     *
     * @param request
     * @return
     */
    private Map<String, TbItem> getCartFromCookie(HttpServletRequest request){
        Map<String, TbItem> hashMap = new HashMap<>();
        String cookieValue = CookieUtils.getCookieValue(request, CART_COOKIE_KEY, true);
        if (StringUtils.isNotBlank(cookieValue)){
            hashMap = JsonUtils.jsonToMap(cookieValue, TbItem.class);
            return hashMap;
        }
        return hashMap;
    }

    /**
     * 查询redis中的购物车信息
     *
     * @param userId
     * @return
     */
    private Map<String, TbItem> getCartFromRedis(String userId){
        Map<String, TbItem> map = cartFeign.selectCartByUserId(userId);
        if (map!=null && map.size()>0){
            return map;
        }
        return new HashMap<String, TbItem>();
    }

    /**
     * 将商品添加到购物车中
     *
     * @param cart
     * @param itemId
     * @param num
     */
    private void addItemToCart(Map<String, TbItem> cart,Long itemId,Integer num){
            TbItem tbItem = cart.get(itemId.toString());
            if (tbItem != null) {
//            购物车商品数量累加
                tbItem.setNum(tbItem.getNum() + num);
                cart.put(itemId.toString(), tbItem);
            } else {
                tbItem = itemFeign.selectItemInfo(itemId);
                tbItem.setNum(num);
                cart.put(itemId.toString(), tbItem);
            }
    }

    /**
     * 购物车加到cookie
     *
     * @param request
     * @param response
     * @param cart
     */
    private void addClientCookie(HttpServletRequest request,HttpServletResponse response,Map<String,TbItem> cart){
        String cartJson = JsonUtils.objectToJson(cart);
        CookieUtils.setCookie(request,response,CART_COOKIE_KEY, cartJson,true);
    }

    /**
     * 添加购物车到redis
     *
     * @param cart
     * @param userId
     * @return
     */
    public boolean addClientRedis(Map<String,TbItem> cart,String userId){
        return cartFeign.insertItemToRedis(userId,cart);
    }
}
